package com.wufun.overseas.main.activity;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.wufun.overseas.R;
import com.wufun.overseas.main.base.MyActivity;
import com.wufun.overseas.utils.ImageCompressor;
import com.wufun.overseas.utils.StringUtils;
import com.wufun.overseas.view.AlbumPopupWindow;
import com.wufun.overseas.view.adapter.MyAlbumAdapter;
import com.wufun.overseas.view.lib.ImageFolder;
import com.wufun.overseas.view.lib.ImageScaner;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xiet on 2015/7/8.
 */
public class MyAlbumActivity extends MyActivity implements View.OnClickListener {
    public static final  String KEY_SELECTED_IMAGES         = "key_selected_images";
    public static final  int    REQUEST_CODE_ALBUM          = 0x0100;
    private static final int    REQUEST_CODE_PICK_IMAGE     = 0x0101;
    private static final int    REQUEST_CODE_CAPTURE_CAMERA = 0x0102;

    private static final String DCIM_PATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera";

    private int              mScreenHeight;
    private AlbumPopupWindow mAlbumPopupWindow;

    private ImageScaner mScaner;
    private List<String> mImages;
    private List<String> mSelectedImages;

    private GridView       mGridView;
    private MyAlbumAdapter mAdapter;

    private View      actionbarLayout;
    private TextView  mAlbumTitle;
    private TextView  mSelectedNum;
    private ImageView mCancelView;
    private Button mOkView;
    private ImageView mCollapseView;

    private ImageFolder currentImageFolder;

    //是否制定拍照路径。默认true，原因：1.部分手机拍照后返回图片可能为空.2.部分返回的为Bitmap，是经过压缩的，质量会差
    private final boolean useSpecifyDestCaptureUri = true;
    private Uri destCaptureUri;

    //default pick size
    private static int MAX_PICK_SIZE;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_album_activity);

        MAX_PICK_SIZE = getIntent().getIntExtra("MAX_PICK_SIZE", 4);

        initWindownParams();

        initViews();
        initAlbumPopupWindow();
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshAlbumImages();
    }

    private void initViews() {
        hideTitleBar();

        mScaner = new ImageScaner(this);
        actionbarLayout = findViewById(R.id.album_title);
        mGridView = (GridView) findViewById(R.id.album_grid);
        mCancelView = (ImageView) findViewById(R.id.back_image);
        mOkView = (Button) findViewById(R.id.ok_image);
        mAlbumTitle = (TextView) findViewById(R.id.layout_title);
        mCollapseView = (ImageView) findViewById(R.id.album_collapse_image);
        mSelectedNum = (TextView) findViewById(R.id.select_num);

        mCancelView.setOnClickListener(this);
        mOkView.setOnClickListener(this);
        ((View) mAlbumTitle.getParent()).setOnClickListener(this);
//        mCollapseView.setOnClickListener(this);

        setCollapse(true);
        mSelectedImages = getSelectedImagesFromIntent(getIntent());
        refreshSelectedImagesFlag();

        initMyAlbumDetail();
    }

    private void refreshSelectedImagesFlag() {
        if (mSelectedImages == null || mSelectedImages.size() == 0) {
            mSelectedNum.setText("0");
            mSelectedNum.setVisibility(View.GONE);
            return;
        }
        mSelectedNum.setVisibility(View.VISIBLE);
        mSelectedNum.setText(mSelectedImages.size() + "");
    }

    private void setCollapse(boolean collapse) {
        if (collapse) {
            mCollapseView.setBackgroundResource(R.drawable.arrow_down);
        } else {
            mCollapseView.setBackgroundResource(R.drawable.arrow_up);
        }
    }

    private void initMyAlbumDetail() {
        if (mImages == null)
            mImages = new ArrayList<String>();
        if (mSelectedImages == null)
            mSelectedImages = new ArrayList<String>();

        currentImageFolder = getPapaAlbum();
        refreshAlbumImages();
    }

    private ImageFolder getPapaAlbum() {
        ImageFolder folder    = new ImageFolder();
        String      papaAlbum = "";

        if (papaAlbum.equals("")) {
            folder = getDciAlbum();
        } else {
            File file = new File(papaAlbum);
            folder.setDir(file.getPath());
            folder.setName(file.getName());
        }

        return folder;
    }

    protected void getImageFromLocalAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");//相片类型
        startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
    }

    protected void getImageFromCamera() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            SimpleDateFormat formatter  = new SimpleDateFormat("yyyyMMdd_HHmmss");
            String           dateString = formatter.format(System.currentTimeMillis());
            File             file       = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/IMG_" + dateString + ".jpg");
            if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
            System.out.println(file.getAbsoluteFile());
            Uri imageUri = Uri.fromFile(file);
            if (useSpecifyDestCaptureUri) {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                destCaptureUri = imageUri;
            }


            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                startActivityForResult(takePictureIntent, REQUEST_CODE_CAPTURE_CAMERA);
            }
        } else {
            Toast.makeText(getApplicationContext(), "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
        }
    }

    private ImageFolder getDciAlbum() {
        ImageFolder folder = new ImageFolder();
//        File dcim = getExternalFilesDir(Environment.DIRECTORY_DCIM);
        File dcim = new File(DCIM_PATH);
        folder.setDir(dcim.getPath());
        folder.setName(dcim.getName());

        return folder;
    }

    private void initWindownParams() {
        DisplayMetrics outMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        mScreenHeight = outMetrics.heightPixels;
    }

    private void initAlbumPopupWindow() {
        View view            = LayoutInflater.from(this).inflate(R.layout.album_layout, null);
        int  popwindowHeight = (int) (mScreenHeight * 0.6);
        popwindowHeight = mScreenHeight - actionbarLayout.getBottom();
        mAlbumPopupWindow = new AlbumPopupWindow(
                this,
                view,
                RelativeLayout.LayoutParams.MATCH_PARENT,
                popwindowHeight);

        mAlbumPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
                setCollapse(true);
            }
        });

        mAlbumPopupWindow.setOnAlbumSelectedListener(new AlbumPopupWindow.OnAlbumSelectedListener() {
            @Override
            public void selected(ImageFolder folder) {
                currentImageFolder = folder;
                refreshAlbumImages();
            }
        });
    }

    private void processAlbumSelected(ImageFolder folder) {
        if (folder != null && new File(folder.getDir()).exists())
            mAdapter = new MyAlbumAdapter(this, mScaner.scanDir(folder.getDir()), folder.getDir(), mSelectedImages);
        else
            mAdapter = new MyAlbumAdapter(this, null, null, mSelectedImages);
        mGridView.setAdapter(mAdapter);
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position < 1) {
                    getImageFromCamera();
                    return;
                }
                MyAlbumAdapter adapter = (MyAlbumAdapter) parent.getAdapter();
                processImageSelect(view, (String) adapter.getItem(position));


            }
        });

        mAlbumTitle.setText(folder.getName());
        setCollapse(true);
        if (mAlbumPopupWindow != null)
            mAlbumPopupWindow.dismiss();
    }

    private void refreshAlbumImages() {
        if (currentImageFolder != null) {
            processAlbumSelected(currentImageFolder);
        }
    }

    public void processImageSelect(View parent, String item) {
        ImageView image = (ImageView) parent.findViewById(R.id.image);
        ImageView flag  = (ImageView) parent.findViewById(R.id.image_flag);
        if (mSelectedImages == null) mSelectedImages = new ArrayList<String>();
        if (mSelectedImages.contains(item)) {
            mSelectedImages.remove(item);
            image.setColorFilter(null);
            flag.setImageResource(R.drawable.pic_select_default);
            refreshSelectedImagesFlag();

            processImageCompress(item, false);
            return;
        }

        if (mSelectedImages.size() == MAX_PICK_SIZE) {
            Toast.makeText(this, "最多选择" + MAX_PICK_SIZE + "张图", Toast.LENGTH_SHORT).show();
        } else {
            mSelectedImages.add(item);
            image.setColorFilter(Color.parseColor("#7f989898"));
            flag.setImageResource(R.drawable.pic_select_selected);
            refreshSelectedImagesFlag();

            processImageCompress(item, true);
        }
    }

    public synchronized void processImageCompress(final String path, final boolean addTask) {
        ImageCompressor.getInstance().compressImage(getApplicationContext(), path, addTask);
    }

    private void showAlbumPopupWindow(View view) {
        mAlbumPopupWindow.setAnimationStyle(R.style.animation_album_popup);
        mAlbumPopupWindow.showAsDropDown(view, 0, 0);
        setCollapse(false);

        // 设置背景颜色变暗
//        WindowManager.LayoutParams lp = getWindow().getAttributes();
//        lp.alpha = .3f;
//        getWindow().setAttributes(lp);

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.back_image) {
            setResultForRequest();
        } else if (id == R.id.ok_image) {
            setResultForRequest();
        } else if (id == R.id.album_collapse_image || id == R.id.layout_title || id == R.id.layout_show_album) {
            showAlbumPopupWindow(findViewById(R.id.album_title));
        }
    }

    private String getCapturePath(Intent data) {
        if (data == null) return "";

        Uri    uri   = data.getData();
        String spath = "";
        if (uri == null) {

            //use bundle to get data
            if (data.hasExtra("data")) {
                Bitmap photo = data.getParcelableExtra("data"); //get bitmap
                //spath :生成图片取个名字和路径包含类型,质量会不太好，因为此处返回的为缩略图

                // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
                Uri tempUri = getImageUri(getApplicationContext(), photo);

                // CALL THIS METHOD TO GET THE ACTUAL PATH
                File finalFile = new File(getRealFilePath(this, tempUri));

                System.out.println(finalFile.getAbsoluteFile());

                spath = finalFile.getAbsolutePath();
            } else {
                Toast.makeText(getApplicationContext(), "拍照失败", Toast.LENGTH_LONG).show();
                return null;
            }
        } else {
            spath = getRealFilePath(this, uri);
        }
        return spath;
    }

    public Uri getImageUri(Context inContext, Bitmap inImage) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
        return Uri.parse(path);
    }

    private String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String       data   = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_PICK_IMAGE:
                break;
            case REQUEST_CODE_CAPTURE_CAMERA:
                if (resultCode != RESULT_OK) break;

                if (mSelectedImages == null) mSelectedImages = new ArrayList<String>();

                String capturedPath = "";
                if (useSpecifyDestCaptureUri && destCaptureUri != null) {
                    capturedPath = getRealFilePath(this, destCaptureUri);
                } else {
                    capturedPath = getCapturePath(data);
                }

                if (!StringUtils.isEmpty(capturedPath)) {
                    if (mSelectedImages != null && mSelectedImages.size() >= MAX_PICK_SIZE) {
                        mSelectedImages.remove(mSelectedImages.size() - 1);
                    }
                    mSelectedImages.add(capturedPath);

                    processImageCompress(capturedPath, true);

                    setResultForRequest();
                } else {
                    Toast.makeText(this, "获取图片失败", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    private void setResultForRequest() {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putSerializable(KEY_SELECTED_IMAGES, (Serializable) mSelectedImages);
        intent.putExtras(bundle);
        setResult(REQUEST_CODE_ALBUM, intent);
        finish();
    }

    private List<String> getSelectedImagesFromIntent(Intent intent) {
        Bundle bundle = intent.getExtras();
        if (bundle == null) return null;

        return (List<String>) bundle.get(MyAlbumActivity.KEY_SELECTED_IMAGES);
    }
}
